<template>  
  <div class="area-management">  
    <el-card class="area-table-card">  
      <div slot="header" class="header-section">
        <div class="title-container" style="width: 100%;">  
            <h2 class="page-title">智慧化污水厂 - 区域管理</h2>  
            <div class="button-group">  

                <el-upload class="excel-upload" :action="uploadUrl" :file-list="fileList" :before-upload="beforeExcelUpload"   
                          :on-success="handleUploadSuccess" :headers="headers" :data="uploadParams" :limit="1"   
                          accept=".xlsx,.xls" list-type="text">  
                    <el-button size="small" type="primary" icon="el-icon-upload" :loading="uploading">  
                        点击上传Excel  
                    </el-button>  
                    <div slot="tip" style="margin: left 30px;" class="upload-tip">  
                        上传文件：区域数据，设备数据，任务数据，保养数据。  
                        <el-link type="primary" :underline="false" @click="downloadTemplate">  
                            下载模板  
                        </el-link>  
                    </div>  
                </el-upload>  
              <!-- <el-button  type="primary" icon="el-icon-plus" @click="showAddModal" class="management-btn">  
                    新增区域  
                </el-button>   -->
            </div>  
       
        </div> 
            
      </div> 
      <!-- 区域列表 -->  
      <el-table :data="areaData" style="width: 120%" border stripe highlight-current-row>  
        <el-table-column prop="areaId" label="区域ID" align="center" width="400" />  
               <el-table-column prop="areaName" label="区域名称" align="center" width="400" /> 

        <el-table-column prop="isDelete" label="是否删除" align="center" v-if="false" width="220" />  

        <el-table-column label="操作" align="center" width="400">  
          <template slot-scope="scope">  
            <el-button disabled type="primary" size="mini" icon="el-icon-edit" @click="showEditModal(scope.row)">编辑</el-button>  
            <el-button  
            disabled
              type="danger"  
              size="mini"  
              icon="el-icon-delete"  
              @click="confirmDelete(scope.row)"  
            >  
              删除  
            </el-button>  
          </template>  
        </el-table-column>  
      </el-table>  
    </el-card>  
   <!-- 进度对话框 -->
    <!-- <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-progress :text-inside="true" :stroke-width="20" :percentage="upload.percent" status="success" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="upload.open = false">关 闭</el-button>
      </span>
    </el-dialog> -->

    <!-- 新增/编辑区域模态框 -->  
    <el-dialog :title="isEditing ? '编辑区域' : '新增区域'" :visible.sync="formDialogVisible" width="500px">  
      <el-form :model="form" :rules="rules" ref="areaForm" label-width="100px">  
        <el-form-item label="区域名称" prop="areaName">  
          <el-input v-model="form.areaName" placeholder="请输入区域名称" />  
        </el-form-item>  
        <el-form-item label="区域描述" prop="areaDescription">  
          <el-input v-model="form.areaDescription" type="textarea" placeholder="请输入区域描述" />  
        </el-form-item>  
        <el-form-item label="地区" prop="region">  
          <el-input v-model="form.region" placeholder="请输入所在地区" />  
        </el-form-item>  
        <!-- <el-form-item label="经度" prop="longitude">  
          <el-input v-model="form.longitude" type="number" placeholder="请输入经度" />  
        </el-form-item>  
        <el-form-item label="纬度" prop="latitude">  
          <el-input v-model="form.latitude" type="number" placeholder="请输入纬度" />  
        </el-form-item>   -->
      </el-form>  
      <div slot="footer" class="dialog-footer">  
        <el-button @click="formDialogVisible = false">取消</el-button>  
        <el-button type="primary" @click="saveArea">保存</el-button>  
      </div>  
    </el-dialog>  
  </div>  
</template>  

<script>  
import { Message, MessageBox } from "element-ui";  
import {list,addRegion,updateRegion} from "@/api/wushui/region";
import { getToken } from "@/utils/auth";  
import { download } from "@/utils/request";  

export default {  
  
  name: "AreaManagement",  
  data() {  
    
    return {  

      uploadUrl: process.env.VUE_APP_BASE_API + "/api/common/uploadPreparation", // 后台接口地址  
      fileList: [],  
      uploading: false,  
      errorFileUrl: "",

      areaData: [],  
      formDialogVisible: false, // 控制模态框显示  
      isEditing: false, // 是否在编辑模式  
      form: {  
        area_id: null,  
        area_name: "",  
        area_description: "",  
        region: "",  
        longitude: "",  
        latitude: "",  
      },  
      rules: {  
        area_name: [  
          { required: true, message: "区域名称不能为空", trigger: "blur" },  
        ],  
        region: [{ required: true, message: "地区不能为空", trigger: "blur" }],  
      },  
    };  
  },  
  computed: {  
    headers() {  
      return {  
        Authorization: "Bearer " + getToken()  
      };  
    },  
    uploadParams() {  
      return {  
        taskId: this.taskId,  
        uploadtype: "records"  
      };  
    }  
  },  
  created(){
    this.getList();

  },
  methods: {  
    // 下载模板  
    async downloadTemplate() {  
      try {  
        // await downloadTemplate();  
        this.download('/api/common/download', {
        }, `模版${new Date().getTime()}.xlsx`)
        this.$modal.msgSuccess("模板下载成功");  
      } catch (error) {  
        console.error("模板下载失败:", error);  
      }  
    },  

    // 上传前校验  
    beforeExcelUpload(file) {  
      const isExcel = /\.(xlsx|xls)$/.test(file.name);  
      const isLt10M = file.size / 1024 / 1024 < 10;  

      if (!isExcel) {  
        this.$modal.msgError("只能上传Excel文件!");  
        return false;  
      }  
      if (!isLt10M) {  
        this.$modal.msgError("上传文件大小不能超过10MB!");  
        return false;  
      }  

      this.uploading = true;  
      return true;  
    },  

    // 处理上传成功  
    handleUploadSuccess(response, file) {  
      console.log(response)
      this.uploading = false;  
      
      if (response.status === 200) {  
        this.$modal.msgSuccess(response.message);  
        this.getList();
      } else {  
        this.$modal.msgError(response.msg || "文件上传失败");  
      }  
      
      this.fileList = []; // 清空已上传文件列表  
    },  

    // 下载错误文件  
    downloadErrorFile() {  
      if (!this.errorFileUrl) return;  
      
      window.location.href = process.env.VUE_APP_BASE_API + this.errorFileUrl;  
    },

    // 获取列表数据
    getList() {
      this.loading = true;
      list(this.formData).then(response => {
        console.log(response)
        this.areaData = response.rows;
        console.log(response)
      });
    },
    // 显示新增区域模态框  
    showAddModal() {  
      this.isEditing = false;  
      this.resetForm();  
      this.formDialogVisible = true;  
    },  
    // 显示编辑区域模态框  
    showEditModal(row) {  
      this.isEditing = true;  
      this.form = { ...row }; // 克隆当前数据到表单  
      this.formDialogVisible = true;  
    },  
    // 重置表单  
    resetForm() {  
      this.form = {  
        area_id: null,  
        area_name: "",  
        area_description: "",  
        region: "",  
        longitude: "",  
        latitude: "",  
      };  
    },  
    // 保存数据（新增或编辑）  
    saveArea() {  
      this.$refs.areaForm.validate((valid) => {  
        if (valid) {  
          if (this.isEditing) { 
            this.form.isDelete = '0'
            // 编辑模式  
            updateRegion(this.form).then((response) => {
              this.getList();
              Message.success("编辑成功！");
            }).catch(() => {
              this.$message.error("获取数据失败");
            });
          } else {  
                        
            // 检查 longitude 范围（-180 到 180）  
            // if (this.form.longitude < -180 || this.form.longitude > 180) {  
            //   this.$message.error("经度值必须在 -180 到 180 之间！");  
            //   return false; // 阻止表单提交  
            // }  

            // // 检查 latitude 范围（-90 到 90）  
            // if (this.form.latitude < -90 || this.form.latitude > 90) {  
            //   this.$message.error("纬度值必须在 -90 到 90 之间！");  
            //   return false; // 阻止表单提交  
            // }  
            // if (isNaN(this.form.longitude) || this.form.longitude === "") {  
             
            //   this.$message.error("经度必须为数字！"); 
            //   return false; // 阻止表单提交  
            // }  

            // // 检查 latitude 是否为数字  
            // if (isNaN(this.form.latitude) || this.form.latitude === "") {  
              
            //   this.$message.error("纬度必须为数字！"); 
            //   return false; // 阻止表单提交  
            // }  
            // 新增模式  
            addRegion(this.form).then((response) => {
              this.getList();
              Message.success("新增区域成功！");  
            }).catch(() => {
              this.$message.error("获取数据失败");
            });
          }  
          this.formDialogVisible = false;  
        }  
      });  
    },  
    // 删除区域  
    confirmDelete(row) {  
      MessageBox.confirm(  
        `确定要删除区域 "${row.area_name}" 吗？`,  
        "提示",  
        {  
          confirmButtonText: "确定",  
          cancelButtonText: "取消",  
          type: "warning",  
        }  
      )  
        .then(() => {  
          row.isDelete = '1'
          updateRegion(row).then((response) => {
              this.getList();
              Message.success("区域已删除！");  
            }).catch(() => {
              this.$message.error("获取数据失败");
            });
        })  
        .catch(() => {  
          Message.info("取消删除");  
        });  
    },  
  },  
};  
</script>  

<style lang="scss" scoped>  

.title-container {  
    padding: 20px;  
    background-color: #f9f9f9;  
    border-radius: 5px;  
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);  
    margin-bottom: 20px;  
}  

.page-title {  
    font-size: 24px;  
    font-weight: bold;  
    color: #333;  
    margin-bottom: 10px;  
}  

.button-group {  
    display: flex;  
    align-items: center;  
    justify-content: space-between;  
}  

.management-btn {  
    margin-right: 20px;  
}  

.excel-upload {  
    display: flex;  
    align-items: center;  
}  

.upload-tip {  
    margin-top: 8px;  
    color: #666;  
    font-size: 12px;  
}  

.upload-container {  
  padding: 15px;  
  border: 1px dashed #d9d9d9;  
  border-radius: 6px;  

  ::v-deep .excel-upload {  
    .el-upload {  
      width: 100%;  
    }  
    .el-upload-list__item-name {  
      color: #1890ff;  
    }  
  }  

  .upload-tip {  
    margin-top: 8px;  
    color: #606266;  
    font-size: 12px;  
    line-height: 1.5;  
  }  

  .import-result {  
    white-space: pre-wrap;  
    line-height: 1.8;  
    padding: 10px;  
    background: #f8f8f9;  
    border-radius: 4px;  
  }  
}   
.area-management {  
  padding: 20px;  
}  

.header-section {  
  display: flex;  
  justify-content: space-between;  
  align-items: center;  
}  

.dialog-footer {  
  text-align: right;  
}  

.area-table-card {  
  margin: 20px 0;  
}  
</style>